package com.hzf.booklibrary.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import com.hzf.booklibrary.ReaderApplication;
import com.hzf.booklibrary.base.Constant;
import com.hzf.booklibrary.bean.Recommend;

import com.hzf.booklibrary.bean.book.Book;
import com.hzf.ftp.DownloadListener;
import com.hzf.ftp.FtpUtils;



import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/4/14.
 */

public class DownloadUtils  {

    private OkHttpClient mOkHttpClient;
    private DownloadBookState mDownloadBookState;
    private String server;
    private int port;
    private String userName;
    private String pwd;

    /**
     * 采用OkHttpClient下载方式的构造方法
     * @param downloadBookState
     */
    public DownloadUtils(DownloadBookState downloadBookState){
        OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(20 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(20 * 1000, TimeUnit.MILLISECONDS)
                .retryOnConnectionFailure(true);// 失败重发
        mOkHttpClient = builder.build();
        mDownloadBookState = downloadBookState;
    }
    public synchronized <T> void downloadBooks(final Book book){
        final File file ;
        LogUtils.e(FileUtils.getTxtFile(book.id,book.chaptersCount));
        if(book.filetype.equals("txt")||book.filetype.equals("TXT")){
//            if(FileUtils.isExistedTxt(book.id,book.chaptersCount)){
//                mDownloadBookState.downloadSuccess();
//                return;}
            file = FileUtils.getTxtFile(book.id,book.chaptersCount);//txt格式图书
        }else if(book.filetype.equals("pdf")||book.filetype.equals("PDF")){
//            if(FileUtils.isExistedPdf(book.id,book.chaptersCount)){
//                mDownloadBookState.downloadSuccess();
//                return;}
            file = FileUtils.getPdfFile(book.id,book.chaptersCount);//pdf格式图书
        }else {
            mDownloadBookState.downloadFailed();
            return;
        }
        String path = book.path;
        Request request = new Request.Builder().url(path).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mDownloadBookState.downloadFailed();
            //    LogUtils.e("下载失败："+file.getAbsolutePath());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is=null;
                byte[] buf = new byte[8092];
                long totalLength = 0;
                long currentLength=0;
                long fileLength=0;
                int len=0;
                FileOutputStream fos=null;
                try {
                    totalLength = response.body().contentLength();
                    if(file.exists()){
                        fileLength = file.length();
                        if(fileLength==totalLength){
                            //文件已经存在并且下载成功
                            mDownloadBookState.downloadSuccess(totalLength,totalLength);
                            return;
                        }
                    }
                    is = response.body().byteStream();
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        currentLength +=len;
                        fos.write(buf, 0, len);
                        mDownloadBookState.downLoading(currentLength,totalLength);
                    //   LogUtils.e("currentLength:"+currentLength+"---"+"totalLength:"+totalLength);
                    }
                    fos.flush();
                 //   covertFileCharset(file, book);
                    mDownloadBookState.downloadSuccess(currentLength,totalLength);
                } catch (IOException e) {
                    mDownloadBookState.downloadFailed();
                //    LogUtils.e("下载失败："+file.getAbsolutePath());
                    if(NetworkUtils.isAvailable(ReaderApplication.getsInstance())){
                        String bookInfo = "提交结果："+"\n书名："+book.name+"\n图书地址："+book.path+"\n下载进度:"+currentLength/totalLength;
                        String collectionInfo = collectDeviceInfo(ReaderApplication.getsInstance());
                        MailUtils.sendEmail(bookInfo+collectionInfo,null);//向服务器邮箱上报错误信息
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    public interface DownloadBookState{
        void downloadSuccess(long currentLength,long totalLength);
        void downloadFailed();
        void downLoading(long currentLength,long totalLength);
    }

    private void covertFileCharset(File file, Recommend.RecommendBooks book) throws Exception {
        if("txt".endsWith(book.filetype)||"TXT".endsWith(book.filetype)){
            String charset= FileCharsetDetector.guessFileEncoding(file);
            if (charset.contains("windows") || charset.contains("WINDOWS")) {
                LogUtils.e("charset搜索=" + charset);
                FileUtils.convertCharset(file,charset,"GB2312");
            }
        }
    }
    /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    public String collectDeviceInfo(Context ctx) {
        StringBuffer info =new StringBuffer();
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                info.append("\nversionName:");
                info.append(versionName);
                info.append("\nversionCode");
                info.append(versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            LogUtils.e("CrashHandleran.NameNotFoundException---> error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                info.append("\n"+field.getName());
                info.append(field.get(null).toString());
            } catch (Exception e) {
                LogUtils.e("CrashHandler.NameNotFoundException---> an error occured when collect crash info", e);
            }
        }
        return info.toString();
    }




    /**
     * 采用FTP下载方式的构造方法
     * @param state
     * @param hostName
     * @param serverPort
     * @param userName
     * @param password
     */
    public DownloadUtils(DownloadBookState state,String hostName, int serverPort, String userName, String password){
        server=hostName;
        port=serverPort;
        this.userName=userName;
        this.pwd=password;
        mDownloadBookState =state;
    }
    public synchronized void downloadFileByFTP(Recommend.RecommendBooks book){
        Map<String,String> paths = new HashMap<String,String>();
        paths.put("server",book.path);
        paths.put("local", FileUtils.getTxtPath(book.id,book.chaptersCount));
        new DownloadThread(book).start();

    }

    private  class DownloadThread extends Thread implements DownloadListener {
        private String serverName;
        private File localFile;
        private Recommend.RecommendBooks book;
        public DownloadThread(Recommend.RecommendBooks book) {
            this.serverName=book.path;
            this.book=book;
            if("txt".equals(book.filetype)){
                this.localFile=FileUtils.getTxtFile(book.id,book.chaptersCount);
            }else if("pdf".equals(book.filetype)){
                this.localFile=FileUtils.getPdfFile(book.id,book.chaptersCount);
                LogUtils.e(localFile.getAbsolutePath());
            }
        }
        @Override
        public void run() {
            try {
                FtpUtils ftp =  new FtpUtils(server,port,userName,pwd);
                ftp.connectServer();
                ftp.setDownloadListener(this);
                ftp.downloadFile(serverName, localFile.getAbsolutePath());
                LogUtils.e( serverName+":::"+localFile.getAbsolutePath());
                ftp.closeServer();
            }catch (Exception ex){
                LogUtils.e(ex);
                mDownloadBookState.downloadFailed();
                if(NetworkUtils.isAvailable(ReaderApplication.getsInstance())){
                    String bookInfo = "提交结果："+"\n书名："+book.name+"\n图书地址："+book.path+"\n图示封面链接："+book.icon_path;
                    String collectionInfo = collectDeviceInfo(ReaderApplication.getsInstance());
                    MailUtils.sendEmail(bookInfo+collectionInfo,null);//向服务器邮箱上报错误信息
                }
                return;
            }
        //    mDownloadBookState.downloadSuccess();
        }

        @Override
        public void onProgressEvent(long l, long l1) {}
    }
}
